const Answer = require('../models/answers')

class Answers {
  async find(ctx) {
    // 每页大小
    const pageSize = Math.max((ctx.query.page_size || 10) * 1, 1)
    // 当前页
    const current = ctx.query.current * 1
    // 偏移量
    const offset = Math.max(current - 1, 0) * pageSize
    // 查询参数
    const reg = new RegExp(ctx.query.q)
    // NOTE: $or 表示二者之一
    const params = { content: reg, question_id: ctx.params.questionId }

    ctx.body = await Answer.find(params).limit(pageSize).skip(offset)
  }

  async findById(ctx) {
    const { fields = '' } = ctx.query
    // example: name;avatar_url;introducation ---> name avatar_url introducation
    const str = fields.replaceAll(';', ' ')
    const answer = await Answer.findById(ctx.params.id).select(str)
    ctx.body = answer
  }

  async create(ctx) {
    ctx.verifyParams({
      content: { type: 'string', required: true }
    })
    const params = {
      ...ctx.request.body,
      answerer: ctx.state.user._id,
      question_id: ctx.params.questionId
    }
    const answer = await new Answer(params).save()
    ctx.body = answer
  }

  async update(ctx) {
    ctx.verifyParams({
      content: { type: 'string', required: false }
    })
    const answer = await Answer.findByIdAndUpdate(
      ctx.params.id,
      ctx.request.body,
      {
        new: true
      }
    )
    ctx.body = answer
  }

  async delete(ctx) {
    await Answer.findOneAndDelete(ctx.params.id)
    ctx.status = 204
  }
}

module.exports = new Answers()
